package com.eascs.banknet.common.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.common.vo.ServerInfo;

/**
 * xml文件读取帮助类
 * @author user
 *
 */
public class XmlHelp {

	private static Logger logger = LoggerFactory.getLogger(XmlHelp.class);
	
	/**
	 * 外部链接地址
	 */
	public static final String URL_CONFIG_FILE = "."+File.separator+"config"+File.separator+"url.cfg.xml";
	
	
	private static StringBuffer errorMessage = new StringBuffer(); 

	public static Element getRootByString(String result) {
		errorMessage.delete(0, errorMessage.length());
		StringReader read = new StringReader(result);
		InputSource source = new InputSource(read);
		SAXBuilder builder = new SAXBuilder(false);
		Element root = null;
		try {
			Document document = builder.build(source);
			root = document.getRootElement();

		} catch (JDOMException e) {
			e.printStackTrace();
			errorMessage.append(e);
		} catch (IOException e) {
			e.printStackTrace();
			errorMessage.append(e);
		}
		return root;

	}


	/**
	 * 获取根节点
	 * 
	 * @param fileName
	 * @return
	 */
	public static Element getRoot(String fileName) {
		SAXBuilder builder = new SAXBuilder(false);
		Element root = null;
		try {
			Document document = builder.build(fileName);
			root = document.getRootElement();
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return root;
	}

	public static String getPath(String path) {
		 XmlHelp.class.getClassLoader().getResourceAsStream(path);
		return path;
	}
	
	/**
	 * JavaBean转换成xml
	 * 默认编码UTF-8
	 * @param obj
	 * @param writer
	 * @return 
	 */
	public static String convertToXml(Object obj) {
		return convertToXml(obj, "UTF-8");
	}

	/**
	 * JavaBean转换成xml
	 * @param obj
	 * @param encoding 
	 * @return 
	 */
	public static String convertToXml(Object obj, String encoding) {
		String result = null;
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			//marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			//marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

			StringWriter writer = new StringWriter();
			marshaller.marshal(obj, writer);
			result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * xml转换成JavaBean
	 * @param xml
	 * @param c
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T converyToJavaBean(String xml, Class<T> c) {
		T t = null;
		try {
			JAXBContext context = JAXBContext.newInstance(c);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			t = (T) unmarshaller.unmarshal(new StringReader(xml));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return t;
	}
	
	/**
	 * 
	 * @param 文件名称
	 * @param 内容
	 * @param 文件夹名称
	 */
	public static void createXml(String fileName,String content,String folderName, ServerInfo ftpinfo) {
		
		String yearmonth = CoreUtils.getSixBitYearMonthDay(new Date());
		
		String datepath = yearmonth.substring(0, 2) + "/"+ yearmonth.substring(2, 4) + "/"+ yearmonth.substring(4, 6) + "/";
		
		String relatedir = "EAO2O" + "/" + datepath+"/"+folderName;
		 
		FTPUtils.uploadFile(CoreUtils.formatString(ftpinfo.getHref()),
				CoreUtils.parseLong(CoreUtils.formatString(ftpinfo.getPort())).intValue(),
				CoreUtils.formatString(ftpinfo.getUsername()),
				CoreUtils.formatString(ftpinfo.getPassword()), relatedir, fileName+".xml",
				InputStream(content));
	}
	
	public static InputStream InputStream(String str){
		   ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
		   return stream;
	}
	
	public static void main(String[] args) {	 	
		//createXml("java", "<string12121>", "BOC001RQ");
	}
	
	
	public static String getXmlString(String path) {
		File file = new File(path);
		String Ls = null;
		try {
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			while ((Ls = br.readLine()) != null) {
				return Ls;
			}
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return Ls;
	}

}
